//
//  SearchFriendsViewController.m
//  AAIM
//
//  Created by awh on 2019/12/12.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "SearchFriendsViewController.h"
#import "FirendsTableViewCell.h"
#import "FriendsInfoViewController.h"
#import "GroupInfoViewController.h"
#import "AttentionPublicViewController.h"
#import "ContactRequestLogic.h"
#import "ContactModel.h"

@interface SearchFriendsViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic,strong)UITableView * searchResultsTable;//搜索历史
@property (nonatomic,strong)NSMutableArray*searchResultsArray;
@property (nonatomic,strong)UISearchBar * searchBar;
@property (nonatomic,strong)MJTableViewNullDataView *nullDataView;
@property (nonatomic,strong) UIView *titleView;
@property (nonatomic,strong)UITextField *textField;
@property (nonatomic,strong)UILabel *searchTitle;
@property (nonatomic,strong)UIView * tipView;
@property (nonatomic,strong)UILabel * tipLabel;

@property (nonatomic,strong)UIView * searchResultView;
@end

@implementation SearchFriendsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    if (!_pageType ||[_pageType isEqualToString:@"searchUserID"]) {
        if (_searchContent) {
            _textField.text = _searchContent;
        }else{
           _textField.placeholder=@"搜索ID";
        }
       
    }else{
//        searchUserID searchGroupName searchService
        if ([_pageType isEqualToString:@"searchGroupName"]) {
            if (_searchContent) {
                       _textField.text = _searchContent;
                   }else{
           _textField.placeholder=@"搜索群聊";
            }
            KWeakSelf;
            MJRefreshAutoNormalFooter * footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                [weakSelf loadMoreData];
            }];
            self.searchResultsTable.mj_footer = footer;
            [footer setTitle:@"正在加载" forState:MJRefreshStateRefreshing];
            [footer setTitle:@"没有更多搜索结果" forState:MJRefreshStateNoMoreData];
        }else{
            _textField.placeholder=@"搜索公众号/服务号";
        }
    }

}

- (void)loadMoreData{
    
    UIEdgeInsets edge = _searchResultsTable.contentInset;

      edge.bottom = 44;
    KWeakSelf;
      [UIView animateWithDuration:0.2 animations:^{

          weakSelf.searchResultsTable.contentInset = edge;

      }];
    if ([_pageType isEqualToString:@"searchUserID"]) {
        [self deleWithFriendData:_textField.text];
    }else if ([_pageType isEqualToString:@"searchGroupName"]){
        [self deleWithGroupData:_textField.text];
    }else{
        
    }
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}
- (void)setupUI {
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setImage:[UIImage imageNamed:@"bar_back1"] forState:UIControlStateNormal];
    [leftBtn setImageEdgeInsets:UIEdgeInsetsMake(-2, 5, -2, -5)];
    leftBtn.jk_touchAreaInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    leftBtn.frame=CGRectMake(0, 0, 30, 44);
    //    leftBtn.backgroundColor=[UIColor redColor];
    [leftBtn addTarget:self action:@selector(leftBtnBtnDidClickAction:) forControlEvents:UIControlEventTouchUpInside];
    //    [leftBtn sizeToFit];
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.gk_navigationItem.leftBarButtonItems = @[leftItem];
    self.gk_navigationItem.titleView = self.titleView;
    
    
    _searchResultsTable=[[UITableView alloc]initWithFrame:CGRectMake(0, NavigationBarHeight, SCREEN_WIDTH,SCREEN_HEIGHT-NavigationBarHeight) style:UITableViewStylePlain];
    _searchResultsTable.delegate=self;
    _searchResultsTable.dataSource=self;
    _searchResultsTable.rowHeight=60;
    _searchResultsTable.tableFooterView=[UIView new];
    _searchResultsTable.showsVerticalScrollIndicator = NO;
    _searchResultsTable.backgroundColor=[UIColor whiteColor];
    [_searchResultsTable registerClass:[FirendsTableViewCell class] forCellReuseIdentifier:@"searchCell"];
    _searchResultsTable.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.searchResultsTable];
    [self.view addSubview:self.nullDataView];
    if ([_pageType isEqualToString:@"searchUserID"] ||[_pageType isEqualToString:@"searchGroupName"]||[_pageType isEqualToString:@"searchService"]) {
        if (_searchIDAry.count == 0) {
            self.nullDataView.hidden = NO;
        }else{
           self.nullDataView.hidden = YES;
        }
    }else{
        UILabel * tipLbl = [[UILabel alloc]init];
        tipLbl.text = @"搜索指定内容";
        tipLbl.textColor = KHEXCOLOR(@"#D8D8D8");
        tipLbl.font = kMainFont(12.f);
        
        [self.view addSubview:tipLbl];
        [tipLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_top).offset(16+kTopHeight);
            make.centerX.equalTo(self.view.mas_centerX);
        }];
        
    }

    _searchTitle=[[UILabel alloc]initWithFrame:CGRectMake(38, NavigationBarHeight+80, SCREEN_WIDTH-53, 30)];
    _searchTitle.text=@"暂无搜索内容";
    _searchTitle.textAlignment=1;
    if ([_pageType isEqualToString:@"searchUserID"] ||[_pageType isEqualToString:@"searchGroupName"]) {
        if (_searchIDAry.count == 0) {
            _searchTitle.hidden=YES;
        }else{
            _searchTitle.hidden=YES;
        }
    }else{
        _searchTitle.hidden=YES;
    }
    
    _searchTitle.font=[UIFont systemFontOfSize:15];
    _searchTitle.textColor=KHEXCOLOR(kGrayColor_99);
    [self.view addSubview:self.searchTitle];
    
    [self.view addSubview:self.tipView];
    [self.tipView addSubview:self.tipLabel];
    _tipView.hidden = YES;
    [_tipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.top.equalTo(self.view.mas_top).offset(kTopHeight);
        make.right.equalTo(self.view.mas_right);
        make.height.offset(56.f);
    }];
    
    if (![_pageType isEqualToString:@"searchUserID"]&&![_pageType isEqualToString:@"searchGroupName"]){
        UIImageView * leftImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"搜索中"]];
        leftImageView.layer.cornerRadius = 5;
        leftImageView.layer.masksToBounds = YES;
        [_tipView addSubview:leftImageView];
        
        [leftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.tipView.mas_left).offset(15.f);
            make.centerY.equalTo(self.tipView.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(30.f, 30.f));
        }];
        
        [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(leftImageView.mas_right).offset(8.0f);
            make.centerY.equalTo(leftImageView.mas_centerY);
            make.right.equalTo(self.tipView.mas_right).offset(-15.f);
        }];
    }
    
    
    
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if (![_pageType isEqualToString:@"searchUserID"] &&![_pageType isEqualToString:@"searchGroupName"]) {
        _tipView.hidden = NO;
        _searchResultsTable.top = _tipView.bottom;
    }
    
    _nullDataView.hidden = YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (![_pageType isEqualToString:@"searchUserID"]&&![_pageType isEqualToString:@"searchGroupName"]) {
        _tipView.hidden = YES;
//        _nullDataView.hidden = NO;
        _searchResultsTable.top = self.view.top;
    }
    _nullDataView.hidden = NO;
    
    _textField.text = nil;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (![NSObject ldy_isEmpty:textField.text]) {
        if ([CommonTools isEmpty:_pageType]) {
            [self searchActionWithKeyWord:textField.text];
        }else if ([_pageType isEqualToString:@"searchUserID"]){
            [self deleWithFriendData:textField.text];
        }else if ([_pageType isEqualToString:@"searchGroupName"]){
            [self deleWithGroupData:textField.text];
        }else if ([_pageType isEqualToString:@"searchService"]){
            
        }
        
        
    }else
    {
        if (![_pageType isEqualToString:@"searchUserID"]&&![_pageType isEqualToString:@"searchGroupName"]) {
            _searchTitle.hidden=YES;
            _tipView.hidden = YES;
            _searchResultsTable.top = self.view.top;
        }
        
        _textField.text = nil;
    }
    return YES;
}

- (void)deleWithFriendData:(NSString *)text{
    
    [ContactRequestLogic requestSearchFriendQueryWithQuery:text Success:^(NSDictionary * _Nonnull Dict) {
                   KWeakSelf;
                   AAIMLog(@"搜索手机号/ID===%@",Dict);
                   NSMutableArray * dataModelArr = [NSMutableArray array];
                   
                   for (NSDictionary * dic in Dict[@"data"][@"list"]) {
                       ContactModel * model = [ContactModel mj_objectWithKeyValues:dic];
                       [dataModelArr addObject:model];
                   }
                   
                   weakSelf.pageType = @"searchUserID";
                   weakSelf.searchIDAry = [NSMutableArray arrayWithArray:dataModelArr];
                   if (weakSelf.searchIDAry.count == 0) {
                       self.nullDataView.hidden=NO;
                   }else{
                       self.nullDataView.hidden=YES;
                   }
        if(weakSelf.searchResultsTable.mj_footer.isRefreshing){

                 [weakSelf.searchResultsTable.mj_footer endRefreshing];

             }
        //当数据小于13条，没有下拉刷新

        if (weakSelf.searchIDAry.count < IS_iPhoneX?13:10) {

            [weakSelf.searchResultsTable.mj_footer endRefreshingWithNoMoreData];

           

        }
                   [weakSelf.searchResultsTable reloadData];
               } failure:^(NSString * _Nonnull errMsg) {
                  self.nullDataView.hidden=NO;
               }];
    
}

- (void)deleWithGroupData:(NSString *)text{
    [ContactRequestLogic  requestSearchGroupNameWithQuery:text Success:^(NSDictionary * _Nonnull Dict) {
                   AAIMLog(@"搜索群聊===%@",Dict);
                   KWeakSelf;
                   NSArray * dataAry =Dict[@"data"];
                   
                   NSMutableArray * dataModelArr = [NSMutableArray array];
                   
                   for (NSDictionary * dic in dataAry) {
                       ContactModel * model =[ContactModel mj_objectWithKeyValues:dic];
                       [dataModelArr addObject:model];
                       
                   }
                   weakSelf.pageType = @"searchGroupName";
                   weakSelf.searchIDAry = [NSMutableArray arrayWithArray:dataModelArr];
                   if (dataModelArr.count == 0) {
                    self.nullDataView.hidden=NO;
                   }else{
                       self.nullDataView.hidden=YES;
                   }
                   if(weakSelf.searchResultsTable.mj_footer.isRefreshing){

                            [weakSelf.searchResultsTable.mj_footer endRefreshing];

                        }
                   //当数据小于12条，没有下拉刷新

                   if (weakSelf.searchIDAry.count < IS_iPhoneX?13:10) {

                       [weakSelf.searchResultsTable.mj_footer endRefreshingWithNoMoreData];


                   }
                   [weakSelf.searchResultsTable reloadData];
               } failure:^(NSString * _Nonnull errMsg) {
                  self.nullDataView.hidden=NO;
               }];
}

-(void)textFieldTextChange:(UITextField*)textField
{
    if (![_pageType isEqualToString:@"searchUserID"]&&![_pageType isEqualToString:@"searchGroupName"]) {

    if (_tipView.hidden == YES) {
        _tipView.hidden = NO;
    }
    NSString * text=[NSString stringWithFormat:@"搜索：%@",textField.text];
    _tipLabel.attributedText =  [self getAttributeWith:@[@"搜索："] string:text orginFont:14 orginColor:KHEXCOLOR(@"#4795EF") attributeFont:14 attributeColor:[UIColor colorWithHexString:@"#262B2F"]];
    }
    _nullDataView.hidden = YES;
}
-(void)searchActionWithKeyWord:(NSString*)keyWord
{
    //    NSLog(@"自己的id：%@",[LoginManager shareLoginManager].userModel.fuuid);
    [self.searchResultsArray removeAllObjects];

    [ContactRequestLogic requestSearchFriendResultsWithfuuid:keyWord Success:^(NSDictionary * _Nonnull Dict) {
        AAIMLog(@"搜索好友===%@",Dict);
        KWeakSelf;
        ContactModel * model = [ContactModel mj_objectWithKeyValues:Dict[@"data"]];
        [weakSelf.searchResultsArray addObject:model];
        FriendsInfoViewController * vc =[[FriendsInfoViewController alloc]init];
        vc.Fuuid = model.fuuid;
        vc.isFriend = [model.isFriend integerValue];

        weakSelf.nullDataView.hidden=YES;
        [weakSelf.navigationController pushViewController:vc animated:YES];

    } failure:^(NSString * _Nonnull errMsg) {

        self.nullDataView.hidden=NO;
        self.tipView.hidden = YES;
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 23;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    //    if ([self.collerType isEqualToString:@"4"]) {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, tableView.frame.size.width - 20, 15)];
    label.backgroundColor =  [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:14];
    label.textAlignment=0;
    label.textColor=KHEXCOLOR(@"#AFAFAF");
    NSString *title ;
    
    if (section==0) {
        if ([_pageType isEqualToString:@"searchUserID"]) {
            title = @"搜索ID";
        }else if([_pageType isEqualToString:@"searchGroupName"]){
            title = @"查找群";
        }else if([_pageType isEqualToString:@"searchService"]){
            title = @"查找公众号/服务号";
        }
    }

    label.text = [NSString stringWithFormat:@"%@", title];
   
    if (![CommonTools isEmpty:title]) {
         [view addSubview:label];
    }
    return view;
}

- (void)toSearchContent{
    NSArray * strAry = [_tipLabel.text componentsSeparatedByString:@"："];
    if (strAry.count>1) {
      [self searchActionWithKeyWord:strAry[1]];
    }else{
        [self showTipHudWithText:@"请重新输入搜索内容"];
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_pageType isEqualToString:@"searchUserID"]) {
        FriendsInfoViewController * vc =[[FriendsInfoViewController alloc]init];
        ContactModel * searchModel = _searchIDAry[indexPath.row];
        vc.Fuuid = searchModel.fuuid;
        vc.isFriend = [searchModel.isFriend integerValue];
//        vc.dataAry = self.searchIDAry;
        [self.navigationController pushViewController:vc animated:YES];
    }else if([_pageType isEqualToString:@"searchGroupName"]){
        GroupInfoViewController * groupInfoVC = [[GroupInfoViewController alloc]init];
        groupInfoVC.groupModel = _searchIDAry[indexPath.row];
        groupInfoVC.pageType = @"searchPageTo";
        [self.navigationController pushViewController:groupInfoVC animated:YES];
    }else if ([_pageType isEqualToString:@"searchService"]){
        AttentionPublicViewController * attentionVC = [[AttentionPublicViewController alloc]init];
        PublicModel * model = _searchIDAry[indexPath.row];
        attentionVC.udid = model.udid;
        [self.navigationController pushViewController:attentionVC animated:YES];
    }
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([_pageType isEqualToString:@"searchUserID"]||[_pageType isEqualToString:@"searchGroupName"] ||[_pageType isEqualToString:@"searchService"]){
        return _searchIDAry.count;
    }else{
        return _searchResultsArray.count;
    }
    
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FirendsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
    if (!cell) {
        cell = [[FirendsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"searchCell"];
    }
    if ([_pageType isEqualToString:@"searchUserID"]){
        cell.model = _searchIDAry[indexPath.row];
        
    }else if([_pageType isEqualToString:@"searchGroupName"]){
        cell.GroupModel = _searchIDAry[indexPath.row];
    }else if ([_pageType isEqualToString:@"searchService"]){
        cell.pubModel = _searchIDAry[indexPath.row];
    } else{
        cell.model = _searchResultsArray[indexPath.row];
    }
    
    
    return cell;
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    [self.textField resignFirstResponder];
}
- (void)leftBtnBtnDidClickAction:(UIButton *)sender {
//    [self.textField resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSAttributedString *)getAttributeWith:(id)sender
                                  string:(NSString *)string
                               orginFont:(CGFloat)orginFont
                              orginColor:(UIColor *)orginColor
                           attributeFont:(CGFloat)attributeFont
                          attributeColor:(UIColor *)attributeColor
{
    __block  NSMutableAttributedString *totalStr = [[NSMutableAttributedString alloc] initWithString:string];
    [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:orginFont] range:NSMakeRange(0, string.length)];
    [totalStr addAttribute:NSForegroundColorAttributeName value:orginColor range:NSMakeRange(0, string.length)];
    
    if ([sender isKindOfClass:[NSArray class]]) {
        
        __block NSString *oringinStr = string;
        __weak typeof(self) weakSelf = self;
        
        [sender enumerateObjectsUsingBlock:^(NSString *  _Nonnull str, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSRange range = [oringinStr rangeOfString:str];
            [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:attributeFont] range:range];
            [totalStr addAttribute:NSForegroundColorAttributeName value:attributeColor range:range];
            oringinStr = [oringinStr stringByReplacingCharactersInRange:range withString:[weakSelf getStringWithRange:range]];
        }];
        
    }else if ([sender isKindOfClass:[NSString class]]) {
        
        NSRange range = [string rangeOfString:sender];
        
        [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:attributeFont] range:range];
        [totalStr addAttribute:NSForegroundColorAttributeName value:attributeColor range:range];
    }
    return totalStr;
}

- (NSString *)getStringWithRange:(NSRange)range
{
    NSMutableString *string = [NSMutableString string];
    for (int i = 0; i < range.length ; i++) {
        [string appendString:@" "];
    }
    return string;
}

- (UIView *)titleView {
    if (!_titleView) {
        _titleView = [[UIView alloc] init];
        _titleView.bounds = CGRectMake(10, 0, SCREEN_WIDTH - 60, 32);
        _titleView.backgroundColor = KHEXCOLOR(kGrayColor_f2);
        [_titleView configLayerWithBorderWidth:0 andWithCornerRadius:5 andWithBorderColor:[UIColor whiteColor]];
        
        UIImageView *imageView = [UIImageView new];
        imageView.image = [UIImage imageNamed:@"icon_sousuo"];
        imageView.frame = CGRectMake(20, 10, 13, 13);
        [_titleView addSubview:imageView];
        
        _textField = [[UITextField alloc] init];
        _textField.font = [UIFont systemFontOfSize:13];
        _textField.frame = CGRectMake(40, 0, SCREEN_WIDTH - 100, 32);
        _textField.returnKeyType = UIReturnKeySearch;
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.delegate = self;
        [_textField addTarget:self action:@selector(textFieldTextChange:) forControlEvents:UIControlEventEditingChanged];
        [_titleView addSubview:_textField];

    }
    return _titleView;
}
-(MJTableViewNullDataView*)nullDataView
{
    if (!_nullDataView) {
        _nullDataView=[[MJTableViewNullDataView alloc]initWithFrame:CGRectMake(0,0*SCALAE, _searchResultsTable.frame.size.width, _searchResultsTable.frame.size.height+kTopHeight)];
        _nullDataView.hidden=YES;
        _nullDataView.backgroundColor=[UIColor whiteColor];
    }
    [_nullDataView setCustomViewFrame:@"空状态" message:@"搜索无结果"];
    return _nullDataView;
}
-(NSMutableArray*)searchResultsArray
{
    if (!_searchResultsArray) {
        _searchResultsArray=[[NSMutableArray alloc]init];
    }
    return _searchResultsArray;
}
- (UIView *)tipView{
    if (!_tipView) {
        _tipView = [[UIView alloc]init];
        _tipView.backgroundColor = [UIColor whiteColor];
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toSearchContent)];
        tap.numberOfTouchesRequired = 1;
        tap.numberOfTapsRequired = 1;
        [_tipView addGestureRecognizer:tap];
    }
    return _tipView;
}

-(UILabel *)tipLabel{
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc]init];
        _tipLabel.attributedText =  [self getAttributeWith:@[@"搜索："] string:@"搜索：" orginFont:14 orginColor:KHEXCOLOR(@"#4795EF") attributeFont:14 attributeColor:[UIColor colorWithHexString:@"#262B2F"]];;
    }
    return _tipLabel;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
